package com.example.im.mvp.presenter

import android.app.ProgressDialog
import android.content.Context
import com.example.im.bean.UserRoom
import com.example.im.common.Enumerate
import com.example.im.db.DatabaseStorage
import com.example.im.bean.EventBusData
import com.example.im.common.Constants
import com.example.im.xmpp.IMConnection
import com.example.im.mvp.base.BasePresenter
import com.example.im.mvp.view.IRoomView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus

class RoomPresenter(mContext: Context, mView: IRoomView?) :
    BasePresenter<IRoomView>(mContext, mView) {

    private var imConnection: IMConnection? = null
    private var dialog: ProgressDialog? = null

    init {
        imConnection = IMConnection.instance!!
        dialog = ProgressDialog(mContext)
        dialog!!.setCanceledOnTouchOutside(false)
        dialog!!.setMessage("请稍候...")
    }

    override fun detachView() {
        super.detachView()
        this.disposable.clear()
    }

    /**
     * 创建群聊
     * */
    fun roomCreate(roomName: String) {
        if (roomName.isEmpty()) {
            getView().onHint("请输入群名")
            return
        }
        val observable = Observable.just(roomName)
            .subscribeOn(Schedulers.io())
            .map {
                imConnection?.setConferenceCreate(it)
            }
            .map {
                imConnection?.setConferenceBook(it)
            }
            .map {
                imConnection?.setConferenceJoin(it)
            }
            .map {
                imConnection?.onBookmarkedConferences(it,Constants.USER_ROOM_SUB_3)
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                getView().onRoomCreateSuccess(it ?: return@subscribe)
            }, {
                getView().onHint(it.message!!)
                dialog?.cancel()
            }, {
                dialog?.cancel()
            }, {
                dialog?.show()
            })
        this.disposable.add(observable)
    }

    /**
     * 群聊邀请
     * */
    fun roomInvite(roomName: String, userRooms: List<UserRoom>) {
        if (userRooms.isEmpty()) {
            getView().onHint("请选择需要加入的成员")
            return
        }
        val observable1 = Observable.just(roomName)
        val observable2 = Observable.fromIterable(userRooms)
            .subscribeOn(Schedulers.io())
            .map { it.jid.toString() }
            .toList()
            .toObservable()
        val observable3 = Observable.zip(
            observable1,
            observable2,
            BiFunction<String, List<String>, Boolean> { t1, t2 ->
                imConnection!!.setConferenceInvite(t1, t2)
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    if (it)
                        getView().onRoomInviteSuccess()
                    else
                        getView().onHint("邀请失败")
                },
                { getView().onHint(it.message!!) }
            )
        this.disposable.add(observable3)
    }

    /**
     * 获取群聊用户
     * */
    fun roomOwners(userRoom: UserRoom) {

        val observable = Observable.just(userRoom)
            .subscribeOn(Schedulers.io())
            .flatMap {
                Observable.fromIterable(imConnection!!.getConferenceOwners(it.account!!))
            }
            .map {
                imConnection!!.getRosterSearch(it.jid.localpartOrNull.intern())
            }
            .observeOn(AndroidSchedulers.mainThread())
            .filter {
                it.isNotEmpty()
            }
            .flatMap {
                Observable.fromIterable(it)
            }
            .map {
                with(UserRoom(), {
                    this.jid = it.getValues("jid")[0].toString()
                    this.account = it.getValues("Username")[0].toString()
                    this.nickname = it.getValues("Name")[0].toString()
                    this.getUserRoom()
                })
            }
            .toList()
            .toObservable()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                getView().onRoomUserSuccess(it)
            }, {
                dialog!!.cancel()
                getView().onHint(it.message!!)
            }, {
                dialog!!.cancel()
            }, {
                dialog!!.show()
            })
        this.disposable.add(observable)
    }

    /**
     * 踢除成员
     * */
    fun roomKick(roomName: String, userRooms: ArrayList<UserRoom>) {
        if (userRooms.isEmpty()) {
            getView().onHint("请选择需要移除的成员")
            return
        }
        val observable = Observable.fromIterable(userRooms)
            .subscribeOn(Schedulers.io())
            .map {
                imConnection!!.setConferenceKick(roomName, it.jid!!)
            }
            .toList().toObservable()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    getView().onRoomKickSuccess()
                },
                {
                    dialog!!.cancel()
                    getView().onHint(it.message!!)
                },
                { dialog!!.cancel() },
                { dialog!!.show() }
            )
        this.disposable.add(observable)
    }



    /**
     * 删除用户聊天记录
     * */
    fun roomrDeleteChat(userRoom: UserRoom) {
        //删除数据库数据
        DatabaseStorage.deleteChatRecordStorage(userRoom)
        //通知聊天列表页面更新
        val busData = EventBusData(
            Enumerate.Handle.list_chat, Enumerate.Action.list_delete, userRoom
        )
        EventBus.getDefault().post(busData)

        getView().onRoomLeaveSuccess()
    }

    /**
     * 退出群聊
     * */
    fun roomLeave(userRoom: UserRoom) {
        val observable = Observable.just(userRoom)
            .subscribeOn(Schedulers.io())
            .map {
                imConnection!!.setConferenceExit(it.account!!, it.jid!!)
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it) {

                    //删除数据库数据
                    DatabaseStorage.deleteUserRoomStorage(userRoom)
                    //通知聊天列表页面更新
                    val busData1 = EventBusData(
                        Enumerate.Handle.list_chat, Enumerate.Action.list_delete, userRoom
                    )
                    EventBus.getDefault().post(busData1)
                    //通知好友列表页面更新
                    val busData2 = EventBusData(
                        Enumerate.Handle.list_group, Enumerate.Action.list_delete, userRoom
                    )
                    EventBus.getDefault().post(busData2)

                    getView().onRoomLeaveSuccess()
                } else getView().onHint("退群失败")
            }, {
                getView().onHint(it.message!!)
            })
        this.disposable.add(observable)
    }



}